package fr.enseirb.mycub.activity.bike;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import fr.enseirb.mycub.PrefManager;
import fr.enseirb.mycub.R;
import fr.enseirb.mycub.activity.AbstractPreferencesActivity;
import fr.enseirb.mycub.activity.MainActivity;
import fr.enseirb.mycub.activity.component.MapOverlayComponent;
import fr.enseirb.mycub.db.BikeDBConstants;
import fr.enseirb.mycub.db.BikeDBHelper;
import fr.enseirb.mycub.db.DBAdapter;
import fr.enseirb.mycub.db.StationsProvider;
import fr.enseirb.mycub.service.ILocationServiceListener;
import fr.enseirb.mycub.service.LocationService;
import fr.enseirb.mycub.service.LocationService.LocationBinder;
import fr.enseirb.mycub.utils.ActivityHelper;
import fr.enseirb.mycub.utils.Utils;
/**
 * @author Eirbmove
 * 
 */
public class StationDetailsActivity extends SherlockActivity implements
		ILocationServiceListener {

	public static final int COMPUTE_DISTANCE = -2;
	public static final int MAPS_NOT_AVAILABLE = 0;
	public static final int NAVIGATION_NOT_AVAILABLE = 1;

	private Cursor mStation = null;
	private TextView mName = null;
	private TextView mDistance = null;
	private TextView mBikes = null;
	private TextView mSlots = null;
	private CheckBox mFavorite = null;
	private ImageView mSpecial = null;
	private ImageView mCb = null;
	private ImageView mNavigate = null;
	private ImageView mInformation = null;
	private ImageView mShowMap = null;
	private Uri mUri = null;
	private int mLatitude;
	private int mLongitude;
	boolean mBound = false;

	private LocationService mService = null;

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocationBinder binder = (LocationBinder) service;
			mService = binder.getService();
			mBound = true;
			mService.addListener(StationDetailsActivity.this);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mBound = false;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//AppGardenAgent.passExam("STATION_DETAILS_ACTIVITY");
		setContentView(R.layout.bike_station_details_layout);
		//setContentView(R.layout.new_bike_station_details_layout);
		mName = (TextView) findViewById(R.id.name);
		mFavorite = (CheckBox) findViewById(R.id.favorite);
		mDistance = (TextView) findViewById(R.id.distance);
		mCb = (ImageView) findViewById(R.id.icone_cb);
		mSpecial = (ImageView) findViewById(R.id.icone_vcub);
		//mAddress = (TextView) findViewById(R.id.address);
		mNavigate = (ImageView) findViewById(R.id.show_navigation);
		mInformation = (ImageView) findViewById(R.id.show_information);
		mShowMap = (ImageView) findViewById(R.id.show_map);
		mInformation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//startInformation();
			}
		});
		mNavigate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startNavigation();
			}
		});
		mShowMap.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showOnMap(mStation.getString(mStation
						.getColumnIndex(BaseColumns._ID)));
			}
		});
	}

	private void showOnMap(Uri uri) {
		Intent intent = new Intent(this, MainActivity.class)
				.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setAction(MapOverlayComponent.ACTION_DETAIL);
		intent.setData(uri);
		startActivity(intent);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
	}

	private void showOnMap(String id) {
		showOnMap(Uri.withAppendedPath(StationsProvider.CONTENT_URI, id));
	}


	void startMaps() {
		Intent intent = Utils.getMapsIntent(mStation.getInt(mStation
				.getColumnIndex(BikeDBConstants.KEY_LATITUDE)), mStation
				.getInt(mStation
						.getColumnIndex(BikeDBConstants.KEY_LONGITUDE)),
				mStation.getString(mStation
						.getColumnIndex(BikeDBConstants.KEY_NAME)));
		if (Utils.isIntentAvailable(intent, this))
			startActivity(intent);
		else
			showDialog(MAPS_NOT_AVAILABLE);
	}

	void startNavigation() {
		Intent intent = Utils.getNavigationIntent(mStation.getInt(mStation
				.getColumnIndex(BikeDBConstants.KEY_LATITUDE)), mStation
				.getInt(mStation
						.getColumnIndex(BikeDBConstants.KEY_LONGITUDE)));
		if (Utils.isIntentAvailable(intent, this))
			startActivity(intent);
		else
			showDialog(NAVIGATION_NOT_AVAILABLE);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case MAPS_NOT_AVAILABLE:
			return new AlertDialog.Builder(this).setCancelable(true).setTitle(
					getString(R.string.not_available)).setMessage(
					(getString(R.string.maps_not_available_summary)))
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).create();
		case NAVIGATION_NOT_AVAILABLE:
			return new AlertDialog.Builder(this).setCancelable(true).setTitle(
					getString(R.string.not_available)).setMessage(
					(getString(R.string.navigation_not_available_summary)))
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).create();
		default:
		return super.onCreateDialog(id);
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		//getActivityHelper().onPrepareDialog(id, dialog);
		super.onPrepareDialog(id, dialog);
	}

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	protected void onPause() {
		mFavorite.setOnCheckedChangeListener(null);
		if (mBound) {
			mService.removeListener(StationDetailsActivity.this);
			unbindService(mConnection);
			mBound = false;
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (PrefManager.mgr.getBoolean(
				AbstractPreferencesActivity.LOCATION_PREFERENCE, true)) {
			startService(new Intent(this, LocationService.class));
			Intent intent = new Intent(this, LocationService.class);
			bindService(intent, mConnection, 0);
		}
		//On r�cup�re l'URI de la station qu'on a post� avec l'intent en lan�ant le changement d'activit�
		handleIntent();
		mStation = managedQuery(mUri, null, null, null, null);
		if (mStation == null) {
			finish();
			return;
		} else {
			mStation.moveToFirst();
		}
		mLatitude = mStation.getInt(mStation
				.getColumnIndex(BikeDBConstants.KEY_LATITUDE));
		mLongitude = mStation.getInt(mStation
				.getColumnIndex(BikeDBConstants.KEY_LONGITUDE));
		mName.setText(mStation.getInt(mStation.getColumnIndex(BaseColumns._ID))
				+ " - "
				+ mStation.getString(mStation
						.getColumnIndex(BikeDBConstants.KEY_NAME)));
		/*mAddress.setText(getString(R.string.address)
				+ " : "
				+ mStation.getString(mStation
						.getColumnIndex(BikeBikeDBConstants.KEY_ADDRESS)));*/
		if(mStation.getInt(mStation.getColumnIndex(BikeDBConstants.KEY_PAYMENT)) == 1)
		mCb.setImageDrawable(getResources().getDrawable(R.drawable.icone_cb));
		else mCb.setImageDrawable(getResources().getDrawable(R.drawable.icone_nocb));
		if(mStation.getInt(mStation.getColumnIndex(BikeDBConstants.KEY_SPECIAL)) == 1)
			mSpecial.setImageDrawable(getResources().getDrawable(R.drawable.vcubplus));
			else mSpecial.setImageDrawable(getResources().getDrawable(R.drawable.vcub));

		if (mStation
				.getInt(mStation.getColumnIndex(BikeDBConstants.KEY_OPEN)) == 0) {
			findViewById(R.id.open_layout).setVisibility(View.GONE);
			findViewById(R.id.closed_layout).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.open_layout).setVisibility(View.VISIBLE);
			findViewById(R.id.closed_layout).setVisibility(View.GONE);
			mBikes = (TextView) findViewById(R.id.bikes);
			mSlots = (TextView) findViewById(R.id.slots);
			int bikes = mStation.getInt(mStation
					.getColumnIndex(BikeDBConstants.KEY_BIKES));
			int slots = mStation.getInt(mStation
					.getColumnIndex(BikeDBConstants.KEY_SLOTS));
			if (bikes == 0) {
				((ImageView) findViewById(R.id.bike_sign))
						.setImageDrawable(getResources().getDrawable(
								R.drawable.no_bike_sign));
				 mBikes.setText("");
				 findViewById(R.id.bike_layout).setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_background_bike_unavailable));
			}
			else mBikes.setText(getResources().getQuantityString(R.plurals.bike,
					bikes, bikes));
			if (slots == 0) {
				((ImageView) findViewById(R.id.parking_sign))
						.setImageDrawable(getResources().getDrawable(
								R.drawable.no_parking_sign));
				mSlots.setText("");
				findViewById(R.id.bike_layout).setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_background_bike_unavailable));
			}
			else mSlots.setText(getResources().getQuantityString(R.plurals.slot,
					slots, slots));
			
			mFavorite.setChecked(mStation.getInt(mStation
					.getColumnIndex(BikeDBConstants.KEY_FAVORITE)) == 1);
		}
		if (mStation != null)
			mStation.moveToFirst();
		mFavorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton button,
					boolean isChecked) {
				BikeDBHelper
						.updateFavorite(
								DBAdapter.getInstance(StationDetailsActivity.this).getDB(),
								mStation.getInt(mStation
										.getColumnIndex(BaseColumns._ID)),
								isChecked);
			}
		});
	}

	private void handleIntent() {
		mUri = getIntent().getData();
	}

	@Override
	public void onLocationChanged(Location location, boolean alert) {
		int distance = Utils.computeDistance(mLatitude, mLongitude, location);
		if (distance != LocationService.DISTANCE_UNAVAILABLE) {
			mDistance.setText(getString(R.string.upper_at) + " "
					+ Utils.formatDistance(distance));
			mDistance.setVisibility(View.VISIBLE);
		} else {
			mDistance.setVisibility(View.GONE);
		}
	}

	@Override
	public void onLocationProvidersChanged(int id) {
		if (!isFinishing()) {
			showDialog(id);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		menu.add("Search")
		.setIcon(R.drawable.ic_action_search).setOnMenuItemClickListener(searchOnClickListener)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		menu.add("Refresh")
		.setIcon(R.drawable.ic_action_refresh).setOnMenuItemClickListener(refreshOnClickListener)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		return super.onCreateOptionsMenu(menu);
	}

	private OnMenuItemClickListener refreshOnClickListener = new OnMenuItemClickListener() {
		public boolean onMenuItemClick(MenuItem item) {
			Log.i("Submenu", "refresh");
//			refreshData();
			//ActivityHelper.startSync(SubMenuActivity.this);
			return false;
		}
	};

	private OnMenuItemClickListener searchOnClickListener = new OnMenuItemClickListener() {
		public boolean onMenuItemClick(MenuItem item) {
			Log.i("Submenu", "search");
			StationDetailsActivity.this.startSearch(null, false, Bundle.EMPTY, false);
			return false;
		}
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			Log.i("BACK", "case home");
			Intent intent = new Intent(this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		default:
			Log.i("BACK", "DEFAULT");
			//ActivityHelper.startSync(this);
			return super.onOptionsItemSelected(item);
		}
	}
}
